package com.eien.phonezwei.service;

import java.util.ArrayList;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.telephony.SmsManager;
import android.widget.Toast;

/**
 * 转发短信服务
 * @author honooon
 */
public class PhoneZweiService extends Service {

	SharedPreferences eSharedPreferences;
	private final long SEND_INTERVAL = 300 * 1000; // 5分钟内不发送
	// private final long SEND_INTERVAL = 10 * 1000; // 5分钟内不发送

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		// eSharedPreferences = getSharedPreferences("PhoneZweiConfig", 0);
		eSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (eSharedPreferences.getBoolean("forwardMissedCall", false)) {
			long lastSend = eSharedPreferences.getLong("lastSend", 0);
			if (System.currentTimeMillis() - lastSend >= SEND_INTERVAL) {
				int missCallCount = readMissCall(this);
				System.out.println("未接来电数量：" + missCallCount);
				if (missCallCount > 0) {
					String sendToNumber = eSharedPreferences.getString("sendToNumber", "");
					if (sendToNumber.equals("")) {
						Toast.makeText(this, "转发失败，目标手机号码不能为空！", Toast.LENGTH_LONG).show();
					} else {
						String missedStr = missedCallToString(this);
						String text = "你有来自" + missedStr + "的共" + missCallCount + "条未接来电！";
						if (missedStr.equals("")) {
							text = "你有" + missCallCount + "条未接来电！";
						}
						System.out.println(text);
						doSendSMS(sendToNumber, text);
					}
					SharedPreferences.Editor mEditor = eSharedPreferences.edit();
					mEditor.putLong("lastSend", System.currentTimeMillis());
					mEditor.commit();
				}
			}
		}
		stopSelf();
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * 发送短信的方法
	 * @param sendToNumber
	 * @param msg
	 */
	private void doSendSMS(String sendToNumber, String msg) {
		if (msg != null) {
			SmsManager sms = SmsManager.getDefault();
			ArrayList<String> texts = sms.divideMessage(msg);
			if (texts.size() <= 1) {
				sms.sendTextMessage(sendToNumber, null, msg, null, null);
			} else if (texts.size() > 1) {
				sms.sendMultipartTextMessage(sendToNumber, null, texts, null, null);
			}
			Toast.makeText(this, "转发至: " + sendToNumber, Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 读取新（未处理）未接来电数量
	 * @param context
	 * @return
	 */
	private int readMissCall(Context context) {
		int result = 0;
		Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, new String[] { Calls.TYPE }, " type=? and new=?",
				new String[] { Calls.MISSED_TYPE + "", "1" }, "date desc");

		if (cursor != null) {
			result = cursor.getCount();
			cursor.close();
		}
		return result;
	}

	/**
	 * 未接来电号码、名字信息生成发送短信的字符串
	 * @param context
	 * @return
	 */
	private String missedCallToString(Context context) {
		String result = "";
		Cursor cursor = context.getContentResolver().query(CallLog.Calls.CONTENT_URI, new String[] { Calls.NUMBER, Calls.CACHED_NAME, Calls.TYPE },
				" type=? and new=?", new String[] { Calls.MISSED_TYPE + "", "1" }, "date desc");
		if (cursor != null) {
			while (cursor.moveToNext()) {
				String numb = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER));
				String name = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME));
				if (name != null) {
					numb = name + "(" + numb + ")";
				}
				if (result.equals("")) {
					result = numb;
				} else {
					result = result + "， " + numb;
				}
			}
			cursor.close();
		}
		return result;
	}
}
